package server

import (
	"chitchat_http/model"
	"chitchat_http/util"
	"crypto/md5"
	"errors"
	"fmt"
	"github.com/doujunyu/gogo/gogo_log"
	"github.com/doujunyu/gogo/sql_aid"
	"github.com/doujunyu/gogo/utility"
	"os"
	"strings"
	"time"
)

// AdminByLogin 登录
func AdminByLogin(userId int64,RemoteAddr string) (map[string]interface{}, error) {

	list := make(map[string]interface{})
	list["user_id"] = userId
	//获取用户习惯
	userPropertySql, args := sql_aid.PgTable(model.TableByUserSign).Field("is_admin").Where("user_id = ?", userId).ToSql()
	userProperty, err := sql_aid.DataToMap(model.PgSql.Query(userPropertySql, args...))
	if err != nil || len(userProperty) == 0 {
		gogo_log.Error("server_AdminByLoginToUsername", "用户登录", err.Error())
		return nil, errors.New("用户不存在1")
	}
	list["property"] = userProperty[0]
	//生成token信息
	tokenToStringOne := fmt.Sprintf("%v", userId) + time.Now().Format("2006-05-04 15:02:01")
	tokenToMd5One := fmt.Sprintf("%x", md5.Sum([]byte(tokenToStringOne)))
	tokenToStringTwo := tokenToMd5One + time.Now().Format("2006-05-04 15:02:01")
	tokenToMd5Two := fmt.Sprintf("%x", md5.Sum([]byte(tokenToStringTwo)))
	token := fmt.Sprintf("%v-%v", userId, tokenToMd5Two)
	//
	tokenStruct := AdminToken{ //token保存信息
		Token:   token,
		AdminId:  userId,
	}
	if err := tokenStruct.TokenBySetToken(); err != nil {
		return nil, err
	}
	list["token"] = token
	//用户表信息
	userSql, args := sql_aid.PgTable(model.TableByUser).Where("id = ?", userId).ToSql()
	userData, err := sql_aid.DataToMap(model.PgSql.Query(userSql, args...))
	if err != nil || len(userData) == 0 {
		gogo_log.Error("server_UserLogin", "用户登录", err.Error())
		return nil, errors.New("用户不存在1")
	}
	http := os.Getenv("SERVER_HTTP")
	userData[0]["avatar"] = util.IsPicturePath(userData[0]["avatar"].(string),http)
	list["user"] = userData[0]
	//用户登录记录
	userUpdate := make(map[string]interface{})
	userUpdate["last_login_ip"] = RemoteAddr
	userUpdate["last_login_time"] = time.Now().Format(time.RFC3339)
	userLoginSql,args := sql_aid.PgTable(model.TableByUserLogin).Where("user_id = ?",userId).UpdateByMap(userUpdate)
	_,err = model.PgSql.Exec(userLoginSql,args...)
	if err != nil {
		gogo_log.Error("server_UserLogin", "user登录更改登录地址错误", err.Error())
		return nil ,errors.New("登录失败")
	}
	return list, nil
}



// AdminByChangeInfo 个人信息更改
func AdminByChangeInfo(userId int64, data map[string]string)error{
	userUpdate := make(map[string]interface{})
	if data["nick"] != "" {
		userUpdate["nick"] = data["nick"]
	}
	if data["avatar"] != "" {
		picturePath := strings.Replace(data["avatar"],os.Getenv("SERVER_HTTP"),"",-1)//去除域名
		pictureNewPath := strings.Replace(picturePath,"common",model.UserByAvatarPath,-1)//从common移出后则不会再删除
		_,_ = utility.CopyFile("."+pictureNewPath,"."+picturePath)
		userUpdate["avatar"] = pictureNewPath
	}
	if data["motto"] != "" {
		userUpdate["motto"] = data["motto"]
	}
	update,args := sql_aid.PgTable(model.TableByUser).Where("id = ?",userId).UpdateByMap(userUpdate)
	_,err :=  model.PgSql.Exec(update,args...)
	if err != nil {
		gogo_log.Error("server_UserByChangeInfo", "更新信息更改失败", err.Error())
		return err
	}
	return nil
}
// AdminByChangePassword 修改密码
func AdminByChangePassword(userId int64, password string) error {
	update := make(map[string]interface{})
	update["password"] = string(util.Hash(password))
	updateSql, rage := sql_aid.PgTable(model.TableByUserLogin).Where("user_id = ?", userId).UpdateByMap(update)
	_, err := model.PgSql.Exec(updateSql, rage...)
	if err != nil {
		gogo_log.Error("server_UserByChangePassword", "登录信息添加失败", err.Error())
		return errors.New("更改失败")
	}
	return nil
}

// AdminByList 用户列表
func AdminByList(input map[string]string) []map[string]interface{} {
	if input["orderBy"] == "" { //默认排序
		input["orderBy"] = "id desc"
	}
	//排序
	goodsSql, arge := sql_aid.PgTable(model.TableByUser).Field("id", "username", "mobile", "nick", "avatar", "last_login_ip", "last_login_time", "time_c").WhereRaw(func(query *sql_aid.PgQuery, i ...interface{}) {
		if i[0].(map[string]string)["nick"] != "" { //用户昵称
			query.Where("nick like ?", "%"+i[0].(map[string]string)["nick"]+"%")
		}
		if i[0].(map[string]string)["username"] != "" { //登录账号
			query.Where("username like %?%", i[0].(map[string]string)["username"])
		}
		if i[0].(map[string]string)["mobile"] != "" { //手机号
			query.Where("mobile like %?%", i[0].(map[string]string)["mobile"])
		}
		//if i[0].(map[string]string)["status"] != "" { //状态:1=正常,2=禁用
		//	query.Where("status = ?", i[0].(map[string]string)["status"])
		//}
	}, input).OrderBy(input["orderBy"]).PageSize(input["page"], input["page_size"]).ToSql()
	goodsData, err := sql_aid.DataToMap(model.PgSql.Query(goodsSql, arge...))
	if err != nil {
		gogo_log.Error("server_UserByList", "用户列表", err.Error())
		return []map[string]interface{}{}
	}
	return goodsData
}

// AdminByInfos 用户信息多个
func AdminByInfos(userId int64, userIds string)[]map[string]interface{}{
	if userIds == "" {
		return []map[string]interface{}{}
	}
	userIdSplit := strings.Split(userIds,",")
	userIdSplitByString := make([]interface{},0)
	for _, s := range userIdSplit {
		userIdSplitByString = append(userIdSplitByString,s)
	}
	userSql, arge := sql_aid.PgTable(model.TableByUser).Field("id", "nick", "avatar", "motto").WhereIn("id",userIdSplitByString...).ToSql()
	userData, err := sql_aid.DataToMap(model.PgSql.Query(userSql, arge...))
	if err != nil {
		gogo_log.Error("server_UserByList", "用户列表", err.Error())
		return []map[string]interface{}{}
	}
	http := os.Getenv("SERVER_HTTP")
	for _, datum := range userData {
		if datum["avatar"] != nil {
			datum["avatar"] = util.IsPicturePath(datum["avatar"].(string),http)
		}
	}
	return userData
}

